package com.glory.dgcpcpda.activity.mfg;

import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.callback.CustomDialogEntityCallBack;
import com.glory.dgcpcpda.entity.CpcMaterialInfoEntity;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.MLotListEntity;
import com.glory.dgcpcpda.entity.MaterielListEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MaterielUpActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etEqpWork)
    FreeUI_ClearEditText etEqpWork;
    @BindView(R.id.etEqpWorkPosition)
    TextView etEqpWorkPosition;
    @BindView(R.id.etMaterielLot)
    FreeUI_ClearEditText etMaterielLot;
    @BindView(R.id.realMLot)
    FreeUI_ClearEditText realMLot;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.ivPositionArrow)
    ImageView ivPositionArrow;
    @BindView(R.id.flPositionList)
    FrameLayout flPositionList;
    @BindView(R.id.realMLotLayout)
    LinearLayout realMLotLayout;

    @BindView(R.id.flPositionList2)
    FrameLayout flPositionList2;
    @BindView(R.id.tvPosition)
    TextView tvPosition;
    @BindView(R.id.ivPositionArrow2)
    ImageView ivPositionArrow2;
    private FreeUI_GeneralPop mPositionPop;
    private List<String> mPositionList;
    private List<String> mMaterielList;
    private FreeUI_GeneralPop mMaterielPop;
    private LotInfoEntity lotinfo;
    private boolean flag;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_materiel_up;
    }

    @Override
    protected void initView() {
        tvTitle.setText("物料Kitting上机");
        setMainLayout(llMain);
        mMaterielList = new ArrayList<>();
        flag=false;
        realMLot.setInputType(InputType.TYPE_NULL);
        String eqpid = getIntent().getExtras().getString("EQPID");
        String position = getIntent().getExtras().getString("POSITION");
        realMLot.setEnabled(false);
        if (eqpid != null) {
            etEqpWork.setText(eqpid);
            requestMaterielList(eqpid);
        }

        if (position != null) {
            etEqpWorkPosition.setText(position);
        }
        mPositionList = new ArrayList<>();
        mPositionList.add("站点一");
        mPositionList.add("站点二");
        tvPosition.setText(mPositionList.get(0));
        etEqpWork.setShowSoftInputOnFocus(false);
        //隐藏键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(getApplicationContext().INPUT_METHOD_SERVICE);
        //隐藏
        imm.hideSoftInputFromWindow(etEqpWork.getWindowToken(), 0);
        etEqpWork.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                // 获取软键盘的显示状态
                boolean isOpen=imm.isActive();
                //判断是否失去焦点
                if(!hasFocus){
                    //判断是否打开软键盘
                    if (isOpen){
                        imm.toggleSoftInput(0,InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }else{
                    //判断是否打开软键盘
                    if (isOpen){
                        //隐藏
                        imm.hideSoftInputFromWindow(etEqpWork.getWindowToken(), 0);
                    }
                }
            }
        });

        initEdit(etEqpWork, s -> requestMaterielList(s));

        initEdit(etMaterielLot,s->requestMaterialInfo(s));

        initEdit(realMLot,s->getName(s));

        initEdit(etLot, s -> {
            //获取lot信息
            LotUtils.searchLotInfo(MaterielUpActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity response) {
                    lotinfo = response;
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "LOTQUERY");
                }
            });
        });
    }

    private void requestMaterielList(String eqpid) {
        FreeUI_EntityCallBack<BaseResponseBean<MaterielListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<MaterielListEntity>>
                (new TypeToken<BaseResponseBean<MaterielListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<MaterielListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    mMaterielList.clear();
                    List<MaterielListEntity.Materiel> positionsetlines = response.body().getResponse().getBody().getPOSITIONSET().getPOSITIONSETLINES();
                    for (MaterielListEntity.Materiel positionsetline : positionsetlines) {
                        mMaterielList.add(positionsetline.getPOSITIONNAME() + "/" + positionsetline.getPOSITIONDESC());
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<MaterielListEntity>> response) {
                super.onError(response);
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("EQUIPMENTID",eqpid);
        map.addProperty("TYPE","EQPPOSITIONSET");
        map.addProperty("ACTIONTYPE","QUERY");
        NetUtils.requestPostNet("CPC.POSITIONMANAGE", "POSITIONMANAGE", this, map, callBack);
    }

    private void requestMaterialInfo(String mlot){

        FreeUI_EntityCallBack<BaseResponseBean<CpcMaterialInfoEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<CpcMaterialInfoEntity>>
                (new TypeToken<BaseResponseBean<CpcMaterialInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<CpcMaterialInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    CpcMaterialInfoEntity.XMLot cpcMaterialInfoEntity = response.body().getResponse().getBody().getXMLot();
                   Map map= (Map) cpcMaterialInfoEntity.getUDF();
                   String materialType=cpcMaterialInfoEntity.getMATERIALTYPE();
                    String supplyType="FALSE";

                   if(map != null){
                       supplyType= (String) map.get("flag");
                       String rcmsg=(String) map.get("rcmsg");
                       if(rcmsg!=null){
                           String rcmLeftTime=(String) map.get("rcmLeftTime");
                           showToast("该树脂距离过期时间还剩"+rcmLeftTime+"分钟,请注意！",false);
                       }
                   }

                   if("REP".equals(materialType)) {

                       if (map != null) {
                           String matSpec = (String) map.get("matSpec");
                           if (StringUtils.isNotEmpty(matSpec)&&matSpec.startsWith("S")) {
                               realMLotLayout.setVisibility(View.VISIBLE);
                               //S系列的光标移动到胶管二维码栏位
                               flag=true;
                               realMLot.setEnabled(true);realMLot.setHint("请扫描供应商小标签");
                               realMLot.setFocusable(true);
                               realMLot.requestFocus();
                               realMLot.setFocusableInTouchMode(true);
                               realMLot.requestFocusFromTouch();
                           } else {
                               //非S系列的光标移到批次栏位，同时胶管二维码栏位禁止编辑
                               flag=false;
                               realMLot.setEnabled(false);realMLot.setHint("不用供应商小标签");
                               etLot.setFocusable(true);
                               etLot.requestFocus();
                               etLot.setFocusableInTouchMode(true);
                               etLot.requestFocusFromTouch();
                           }
                       }
                   }else if("TRUE1".equals(supplyType)){//丝材框架
                       realMLotLayout.setVisibility(View.VISIBLE);
                       //S系列的光标移动到胶管二维码栏位
                       flag=true;
                       realMLot.setEnabled(true);realMLot.setHint("请扫描供应商小标签");
                       realMLot.setFocusable(true);
                       realMLot.requestFocus();
                       realMLot.setFocusableInTouchMode(true);
                       realMLot.requestFocusFromTouch();
                   } else{


                       //非REP的光标移到批次栏位，同时胶管二维码栏位禁止编辑
                       flag=false;
                       realMLot.setEnabled(false);realMLot.setHint("不用扫描供应商小标签");
                       etLot.setFocusable(true);
                       etLot.requestFocus();
                       etLot.setFocusableInTouchMode(true);
                       etLot.requestFocusFromTouch();
                   }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<CpcMaterialInfoEntity>> response) {
                super.onError(response);
                System.out.println("456123");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("MLOTID",mlot);
        map.addProperty("ACTIONTYPE","QUERYBYID");
        NetUtils.requestPostNet("CPC.FINDMLOTBYID", "TRANSFERMES",this, map, callBack);
    }

    private void getName(String realCharacter){


        if(StringUtils.isNotEmpty(realCharacter)){
            if("REP".equals(etEqpWorkPosition.getText().toString())){
                if(!realCharacter.contains(";")){
                    showToast("胶管二维码内容格式不对，请重新扫描",false);
                }else {
                    String str = realCharacter.split(";")[0].replace("(", "").replace(")", "") + "/" + realCharacter.split(";")[1];
                    realMLot.setText(str);
                    etLot.setFocusable(true);
                    etLot.requestFocus();
                    etLot.setFocusableInTouchMode(true);
                    etLot.requestFocusFromTouch();
                }
            }else{
                realMLot.setText(realCharacter);
                etLot.setFocusable(true);
                etLot.requestFocus();
                etLot.setFocusableInTouchMode(true);
                etLot.requestFocusFromTouch();
            }
        }
    }
    @Override
    protected void initData() {
    }

    @OnClick({R.id.tvBaseSubmit, R.id.ivPositionArrow,R.id.ivPositionArrow2})
    public void onViewClicked(View v) {
        if (v.getId() == R.id.tvBaseSubmit) {
//            if (actionControl("Submit14")) {
//                return;
//            }

            if (getText(etEqpWork).equals("") || etEqpWorkPosition.getText().toString().equals("") || getText(etMaterielLot).equals("")) {
                showToast("填写未完成，请填写相关数据", false);
                return;
            }

            if(lotinfo == null){
                showToast("批次需要扫描，并且是否回车按下！！！", false);
                return;
            }

            String state = lotinfo.getLOT().getSTATE();
            if("待投产".equals(state)){
                showConfirmDialog(MaterielUpActivity.this,"批次处于待投产状态");
                return;
            }

            showSubmitDialog(new onSubmitListener() {
                @Override
                public void setOnSubmitListener() {
                    FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<JSONObject>>
                            (new TypeToken<BaseResponseBean<JSONObject>>() {
                            }.getType(), getSupportFragmentManager(), this) {

                        @Override
                        public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {

                            super.onSuccess(response);
                            if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                                showToast("物料上机成功", true);
                                MaterielUpActivity.this.finish();
                            }
                           /* else{
                                        if("EMC".equals(etEqpWorkPosition.getText().toString())) {
                                            if (!"On".equals(lotinfo.getLOT().getHOLDSTATE())) {
                                                FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                                                        (new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                                                        }.getType(), getSupportFragmentManager(), this) {

                                                    @Override
                                                    public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                                                        super.onSuccess(response);
                                                        showToast("扫描树脂与随件单不匹配，该批次已被扣住，请联系品质进行处理", true);

                                                    }

                                                    @Override
                                                    public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                                                        super.onError(response);
                                                    }
                                                };

                                                JsonObject map = new JsonObject();
                                                map.addProperty("ACTIONTYPE", "HOLDLOTBYLOTID");
                                                map.addProperty("LOTID", lotinfo.getLOT().getLOTID());
                                                NetUtils.requestPostNet("CPC.LOTQUERY", "LOTQUERY", this, map, callBack);
                                            }else{
                                                showToast("该批次已被扣住，请先解扣在上机", true);
                                            }
                                        }
                            }*/
                        }

                        @Override
                        public void onError(Response<BaseResponseBean<JSONObject>> response) {

                            super.onError(response);
                        }
                    };
                    JsonObject map = new JsonObject();
                    map.addProperty("ACTIONTYPE", "ATTACH");
                    map.addProperty("SITE", tvPosition.getText().toString());
                    MLotListEntity mLotListEntity = new MLotListEntity(getText(etMaterielLot), etEqpWorkPosition.getText().toString());
                    List<MLotListEntity> list = new ArrayList<>();
                    list.add(mLotListEntity);
                    map.add("MLOTLIST", new JsonParser().parse(new Gson().toJson(list)).getAsJsonArray());
                    map.addProperty("EQUIPMENTID", getText(etEqpWork));
                    map.addProperty("POSITIONNAME", etEqpWorkPosition.getText().toString());
                    map.addProperty("LOTID", getText(etLot));
                    map.addProperty("CUSTOMERCODE", lotinfo.getLOT().getCUSTOMERCODE());
                    map.addProperty("LINEID", lotinfo.getLINEID());
                    map.addProperty("REALREPINFO", getText(realMLot));
                    NetUtils.requestPostNet("CPC.MLOTKITTING", "MLOTKITTING", this, map, callBack);
                }
            });

        } else if (v.getId() == R.id.ivPositionArrow) {
            if (mMaterielList.size() <= 0){
                showToast("未获取到物料上料位列表",false);
            }

            mMaterielPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flPositionList.getWidth(), mMaterielList, ivPositionArrow, (codeS, i) -> {
                etEqpWorkPosition.setText(codeS.split("/")[0]);
            });
            FreeApi_PopUtils.setArrowShow(ivPositionArrow);
            mMaterielPop.showAsDropDown(flPositionList, 0, 0);
        }else if(v.getId() == R.id.ivPositionArrow2){
            if (mPositionList.size() <= 0){
                showToast("未获取到站点列表",false);
                return;
            }

            if (mPositionPop != null) {
                if (mPositionPop.isShowing()) {
                    mPositionPop.dismiss();
                }
            } else {
                mPositionPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flPositionList2.getWidth(), mPositionList, ivPositionArrow2, (codeS, i) -> {
                    tvPosition.setText(codeS);
                });
            }
            FreeApi_PopUtils.setArrowShow(ivPositionArrow2);
            mPositionPop.showAsDropDown(flPositionList2, 0, 0);
        }
    }


}
